//
//  WKBaseViewController.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/9.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  WKWebView基础类

import UIKit
import WebKit


protocol WKBaseDelegate {
    func server()
}

class WKBaseViewController: BaseViewController,WKNavigationDelegate,WKUIDelegate,ShareVCDelegate,WKScriptMessageHandler {
    
    var webView: WKWebView!
    
    //全局链接变量
    var url : String = ""
    
    var refreshControl = UIRefreshControl()
    var progressView = UIProgressView()
    var urlRequestCache = NSURLRequest()

    
    //分享变量
    var titleStr : String = ""
    var desc : String = ""
    var link : String = ""
    var imgURL : String = ""
    
    
    //刷新图片
    var imgView = UIImageView()
    
    //取出token
    var token : String = ""
    
    
    var viewController = ShareViewController()
    
    //代理
    var wkDelegate : WKBaseDelegate?
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        /**
         ## 进来页面先检测是否有网络
         */
        TestNet.shared.getNetStatus(comfun: { (result) in
            if result.rawValue == "worked" {
            
//                DispatchQueue.main.async {
                    self.imgView.removeFromSuperview()
//                }
                
            } else {
                
                self.addImg()
            }
            
        })

    }
    
    func addImg() -> Void {
        imgView = UIImageView()
        imgView.frame = webView.bounds
        imgView.backgroundColor = UIColor.red
        
        let tag = UITapGestureRecognizer.init(target: self, action:#selector(WKBaseViewController.imgSEL))
        
        imgView.isUserInteractionEnabled = true
        
        imgView.addGestureRecognizer(tag)
        
        webView.scrollView.addSubview(imgView)
        //        view.insertSubview(imgView, aboveSubview: self.webView)
        
    }
    
    func imgSEL() -> Void {
        
        //图片的显示由网络决定
        TestNet.shared.getNetStatus(comfun: { (result) in
            if result.rawValue == "worked" {
                
                
//                DispatchQueue.main.async {
                    self.imgView.removeFromSuperview()
//                }

                self.webView.reload()
                
                self.webView.scrollView.isScrollEnabled = true
            } else {
                
            }
        })
        
        
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //取出本地token，进行拼接,token为空不为空，均传到服务器
        if (localSave.object(forKey: userToken) != nil) {
            token = localSave.object(forKey: userToken) as! String
        } else {
            token = ""
        }
        
        
        //配置webview
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()

        
        //添加交互条目
        //分享到微信
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        //微信支付
        userContentController.add(self as WKScriptMessageHandler, name: "wxpay")
        
        //支付宝支付
        userContentController.add(self as WKScriptMessageHandler, name: "alipay")
        
        //登陆
        userContentController.add(self as WKScriptMessageHandler, name: "login")
        
        //跳转到购物车
        userContentController.add(self as WKScriptMessageHandler, name: "gotoCart")
        
        //确认提交建议
        userContentController.add(self as WKScriptMessageHandler, name: "submit")

        
        //交易记录
        userContentController.add(self as WKScriptMessageHandler, name: "detailRocord")
        
        //返回首页
        userContentController.add(self as WKScriptMessageHandler, name: "backToMain")
        
        //购物车列表
        userContentController.add(self as WKScriptMessageHandler, name: "getCartList")
        
        configuration.userContentController = userContentController

        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        configuration.preferences.javaScriptEnabled = true
        configuration.processPool = WKProcessPool()
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
//        webView.uiDelegate = self
        webView.navigationDelegate = self
        
        view.addSubview(webView)
        
        //添加进度条
        self.progressView = UIProgressView()
        self.progressView.frame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 10)
        view.addSubview(self.progressView)
        self.progressView.progressTintColor = UIColor.orange
        
        //添加刷新控件
        refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
        webView.scrollView.addSubview(refreshControl)

    }
    
    
    deinit {
        
        if self.isViewLoaded {
            self.webView.navigationDelegate = nil
        }
        
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        let msg = message.name
        
        
        
        if  msg == "shareWeixinInfo" {
            
            //将获取到的数据解析成字典
            let messageDic = message.body as! NSDictionary
            
            //解析取回的字典数据
            titleStr = messageDic["title"] as! String
            desc = messageDic["desc"] as! String
            link = messageDic["link"] as! String
            imgURL = messageDic["imgUrl"] as! String
            
            
            viewController = ShareViewController()
            viewController.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
            viewController.delegate = self
            
            self.present(viewController, animated: true, completion: nil)
            
        } else if msg == "wxpay" {
            
            print(message.body)
            
            let dic = message.body
            print("wxpay")
            
            let dicStr = ((message.body) as! String).data(using: .utf8)
            
            
            do
            {
                let daaaa = try JSONSerialization.jsonObject(with: dicStr! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
                print(daaaa)
                WXTool.shared.sendWXPay(wxDict: daaaa)
            } catch {
                
            }

            ///支付宝
        } else if msg == "alipay" {
            
            let dic = message.body as! NSDictionary
            
            var signStr = ""
            
            if ((dic["sign"] as? String) != nil) {
                signStr = dic["sign"] as! String
                
            }
            
            
            //接收Web支付回调
            PaymenyModel.shared.alipay(orderString: signStr, comfun: { (dic) in
                
                print("\((#file as NSString).lastPathComponent):(\(#line))")
                print(dic)
                
                self.webView.evaluateJavaScript("callJsAlert('\(dic)')", completionHandler: nil)
            })
            
            NotificationCenter.default.addObserver(self, selector: #selector(WKBaseViewController.info(notification:)), name: NSNotification.Name(rawValue: "123"), object: nil)
            
        } else if msg == "gotoCart" {
            print("跳转购物车")
            
            jumpToShop()
        } else if msg == "login" {
            
            
            print("login",message.body)
            self.navigationController?.pushViewController(LoginView(), animated: true)
            
            shoppingCarArray.add(message.body)
            
        } else if msg == "submit" {

            print("submit")
            self.wkDelegate?.server()
            
        } else if msg == "detailRocord" {
            print("detailRocord")
            self.navigationController?.pushViewController(JiaoYIVC(), animated: true)
            
        } else if msg == "backToMain" {
            print("backToMain")
            self.navigationController?.pushViewController(MainPageViewController(), animated: true)
            
            //调到购物车
        } else if msg == "getCartList" {
            
            
            print("getCartList")
            let carList = message.body as! NSString
            
            //辨别是否为字符串类型
            if carList.isKind(of: String.self as! AnyClass) {
                //赋值给购物车
                ShoppingModel.shared.shopList = carList as String
            } else {
                print("返回值不是String，或本地错误")
            }

        }
        
    }
    
    //跳转到购物车页面
    func jumpToShop() -> Void {
        let tabBarController = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 3
    }
    
    
    //刷新函数
    func refreshWebView(sender: UIRefreshControl) {
        print("refersh")

        
        
        
        TestNet.shared.getNetStatus { (result) in
            
            if result.rawValue == "worked" {
                self.refreshControl.attributedTitle = NSAttributedString(string: "下拉刷新")
                
//                DispatchQueue.main.async {
                    self.imgView.removeFromSuperview()
//                }

                self.webView.scrollView.isScrollEnabled = true
                
//                DispatchQueue.main.async {
                    self.webView.reload()
                
//                }
//                self.webView.load(NSURLRequest.init(url: URL.init(string: self.url)!) as URLRequest)
                
                sender.endRefreshing()
            } else {
                
                self.addImg()
                self.webView.scrollView.isScrollEnabled = false
                
                self.refreshControl.attributedTitle = NSAttributedString(string: "请检查网络设置")
                
                self.webView.reload()
                sender.endRefreshing()
            }
        }

    }
    
    
    //获取标题
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.progressView.progress = Float(webView.estimatedProgress)
        self.navigationItem.title = self.webView.title
        
        if self.webView.isLoading == false {
            UIView.animate(withDuration: 0.5, animations: {
                self.progressView.alpha = 0
            })
        }
    }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        decisionHandler(.allow)
    }
}

// MARK:- 分享类型
extension WKBaseViewController {
    func shareType(__data: Int) {
        
        viewController.dismiss(animated: true, completion: nil)
        
        switch __data {
        case 100:
            print("QQ 好友")
            QQTool.shared.qqShare(title: titleStr, desc: desc, link: link, imgUrl: imgURL, type: QQApiURLTargetTypeAudio)
        case 101:
            print("QQ 空间")
            QQTool.shared.qqShare(title: titleStr, desc: desc, link: link, imgUrl: imgURL, type: QQApiURLTargetTypeAudio)
//            QQTool.shared.share()
        case 102:
            print("朋友圈")
            
            print(titleStr)
            WXTool.shared.shareText(title: titleStr, desc:desc, link: link, imgUrl: imgURL, shareType: 1)
        case 103:
            print("微信好友")
            WXTool.shared.shareText(title: titleStr, desc:desc, link: link, imgUrl: imgURL, shareType: 0)
        default:
            break
        }
    }
    
}

// MARK:- 接收支付宝app接收结果
extension WKBaseViewController {
    func info(notification : NSNotification) -> Void {
        print("接收通知")
        let dic = notification.userInfo as! [AnyHashable : NSObject] as NSDictionary
        
        let result = dic["re"] as! String
        print(result)
        
        self.webView.evaluateJavaScript("callJsAlert('\(result)')", completionHandler: nil)
        
        
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "123"), object: nil)
    }
}
